package net.adst.util;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 01.11.12
 * Time: 6:56
 * To change this template use File | Settings | File Templates.
 */
public class Lock {
//    private static final Logger log = Logger.getLogger(ResourceManager.class);

    /**
     * Tries to create file anf lock it
     * @return true if lock file locked (app wasn't running), and false if app already running
     */
    public static boolean tryLock() {
        try {
            final String tmpDir = System.getProperties().getProperty("java.io.tmpdir");
            final File file = new File(tmpDir + "ors.lock");
            final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            final FileLock fileLock = randomAccessFile.getChannel().tryLock();
            if (fileLock != null) {
                Runtime.getRuntime().addShutdownHook(new Thread() {
                    public void run() {
                        try {
                            fileLock.release();
                            randomAccessFile.close();
                            file.delete();
                        } catch (Exception e) {
//                            log.warn(e);
                        }
                    }
                });
                return true;
            }
        } catch (Exception e) {
//            log.warn(e);
        }
        return false;
    }

}
